package club.pinea.handler.game;

import club.pinea.annotations.Head;
import club.pinea.interfaces.TCPMessage;
import club.pinea.proto.BasicProto;
import club.pinea.proto.CommandProto;
import club.pinea.proto.GameProto;
import club.pinea.send.MessageSend;
import club.pinea.service.UserService;
import club.pinea.session.GlobalServerPlayerContainer;
import club.pinea.session.IOSession;
import club.pinea.session.ServerPlayer;
import club.pinea.util.GameUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Head(CommandProto.Command.C_S_GET_SCORE_VALUE)
public class GetScoreHandler implements TCPMessage<BasicProto.BaseMessage> {

    @Autowired
    private UserService userService;

    @Override
    public void doMessage(BasicProto.BaseMessage msg, IOSession session) throws Exception {
        ServerPlayer serverPlayer = GlobalServerPlayerContainer.getServerPlayer(session);
        GameUtil gameUtil = serverPlayer.getGameUtil();
        Integer gameScore = gameUtil.getGameScore();
        Integer payScore = gameUtil.getScore();
        if (gameScore > 0) {
            userService.updateMoney(gameScore, serverPlayer.getUserId());
        }
        // 更新座位的游戏记录
        userService.updateSeatDoubleScore(payScore, gameScore, serverPlayer.getSeatId());
        long score = userService.getMoneyById(serverPlayer.getUserId());
        serverPlayer.setGameUtil(null);
        serverPlayer.getUser().setMoney(score);
        GameProto.GetScoreResponse response = GameProto.GetScoreResponse.newBuilder()
                .setRes(MessageSend.successRes())
                .setScore(score)
                .build();
        MessageSend.sendToUser(response, session);
    }
}
